<template>
  <!-- 故障类别设备厂家分析 -->
  <a-spin :spinning="loading">
    <div class="stationFailureAnalysis">
      <div class="titleBar">
        <div class="title">
          故障类别设备厂家分析
          <div class="dateRange">
            <div class="faultType">
              <a-select
                v-model:value="faultType"
                @change="handleFaultTypeChange"
                size="small"
                style="width: 120px; margin-left: 5px"
                placeholder="故障类别"
                allowClear
              >
                <a-select-option
                  v-for="item in faultTypeList"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-select-option
                >
              </a-select>
            </div>
            <a-range-picker
              v-model:value="dateRange"
              size="small"
              :allowClear="false"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              style="margin-right: 8px"
            />
            <a-button
              size="small"
              type="primary"
              class="queryBtn"
              @click="outageDashboardData"
              >查询</a-button
            >
            <a-button size="small" type="link" @click="handleReset"
              >重置</a-button
            >
          </div>
        </div>
      </div>
      <div class="content">
        <div class="topCharts">
          <div class="liquidChart">
            <div class="chartTitle">平均故障次数/MWh</div>
            <div ref="manufacturerChartsRef" class="chartContainer"></div>
          </div>
          <div class="rankList">
            <div class="chartTitle">故障次数/MWh top5电站</div>
            <div class="rankItems">
              <template v-if="faultNumTop5?.length > 0">
                <div
                  class="rankItem"
                  v-for="(item, index) in faultNumTop5"
                  :key="index"
                >
                  <div class="rankNum" :class="`rank${index + 1}`">
                    {{ index + 1 }}
                  </div>
                  <div class="stationName" :title="item.stationName">
                    {{ item.stationName }}
                  </div>
                  <div class="manufacturer">{{ item.supplierName }}</div>
                  <div class="faultCount">{{ item.avgFaultNum }}次/MWh</div>
                </div>
              </template>
              <div class="noData" v-else>
                <div class="noDataText">暂无数据</div>
              </div>
            </div>
          </div>
        </div>
        <div class="bottomChart">
          <div class="chartTitle">{{ bottomChartTitle }}</div>
          <div ref="barChartRef" class="chartContainer"></div>
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script setup>

import * as echarts from "echarts";
import dayjs from "dayjs";
const $api = inject("$api");
const getDefaultDateRange = () => {
  // 默认选上月的1号到上月的最后一天
  const end = dayjs().subtract(1, "month").endOf("month");
  const start = dayjs().subtract(1, "month").startOf("month");
  return [start.format("YYYY-MM-DD"), end.format("YYYY-MM-DD")];
};
const dateRange = ref(getDefaultDateRange());
const chartData = ref();
const manufacturerChartsRef = ref(null);
const barChartRef = ref(null);
const faultType = ref(null);
let manufacturerChart = null;
let barChart = null;
const faultNumTop5 = ref([]);
const bottomChartTitle = ref("所有厂商 - 故障细分统计");
const selectedBarIndex = ref(-1);
const initManufacturerBarCharts = () => {
  if (!manufacturerChartsRef.value) return;
  if (manufacturerChart) {
    manufacturerChart.dispose();
  }
  manufacturerChart = echarts.init(manufacturerChartsRef.value);
  // 检查数据是否存在
  if (
    !chartData.value?.avgFaultNum ||
    Object.keys(chartData.value.avgFaultNum).length === 0
  ) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    manufacturerChart.setOption(option);
    return;
  }

  const chartInfo = Object.entries(chartData.value.avgFaultNum).map(
    ([label, value]) => ({
      value,
      label,
    })
  );

  const manufacturers = chartInfo.map((item) => item.label) || [];
  const values = chartInfo.map((item) => item.value) || [];
  const defaultColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: "#00E5FF" },
    { offset: 1, color: "#0077FF" },
  ]);
  const highlightColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: "#FF9F43" },
    { offset: 1, color: "#FF7A00" },
  ]);
  const seriesData = values.map((value) => ({
    value,
    itemStyle: {
      color: defaultColor,
      borderRadius: 8,
    },
  }));
  const option = {
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "12%",
      containLabel: true,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
    },
    xAxis: {
      type: "category",
      data: manufacturers,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        margin: 10,
      },
    },
    yAxis: {
      type: "value",
      min: 0,
      splitNumber: 4,
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        // formatter: (value) => Math.round(value),
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: "#334155",
          type: "dotted",
        },
      },
      axisLine: {
        show: false,
      },
    },
    series: [
      {
        name: "平均故障次数",
        type: "bar",
        data: seriesData,
        barWidth: "15",
        itemStyle: {
          color: defaultColor,
          borderRadius: 20,
          borderColor: "rgb(0, 214, 248)",
          borderWidth: 1,
        },
        emphasis: {
          itemStyle: {
            borderColor: "rgb(0, 255, 255)",
            borderWidth: 1,
            shadowColor: "rgba(0, 255, 255, 0.5)",
            shadowBlur: 3,
          },
        },
        showBackground: true,
        backgroundStyle: {
          color: "transparent",
          borderRadius: 20,
          borderColor: "rgba(0, 214, 248, 0.3)",
          borderWidth: 1,
          borderType: "solid",
        },
      },
    ],
  };
  manufacturerChart.setOption(option);
  manufacturerChart.on("click", function (params) {
    if (params.componentType === "series" && params.seriesType === "bar") {
      const supplierName = params.name;
      const clickedDataIndex = params.dataIndex;
      const currentOption = manufacturerChart.getOption();
      const currentSeriesData = currentOption.series[0].data;

      if (selectedBarIndex.value === clickedDataIndex) {
        // 取消选中恢复默认标题和数据
        currentSeriesData[clickedDataIndex].itemStyle.color = defaultColor;
        selectedBarIndex.value = -1;
        bottomChartTitle.value = "所有厂商 - 故障细分统计";
        faultNumTop5.value = chartData.value.faultNumTop5 || [];
        // 重新初始化下方图表显示所有厂商数据
        initBarChart();
      } else {
        // 选中新的厂商
        currentSeriesData.forEach((item, index) => {
          if (index === clickedDataIndex) {
            item.itemStyle.color = highlightColor;
          } else {
            item.itemStyle.color = defaultColor;
          }
        });
        selectedBarIndex.value = clickedDataIndex;
        bottomChartTitle.value = `${supplierName} - 故障细分统计`;
        faultNumTop5.value =
          chartData.value.supplierFaultNumTop5?.[supplierName] || [];
        initBarChart(supplierName);
      }
      manufacturerChart.setOption({
        series: [
          {
            data: currentSeriesData,
          },
        ],
      });
    }
  });
};

const initBarChart = (supplierName = null) => {
  if (!barChartRef.value) return;

  if (barChart) {
    barChart.dispose();
  }

  barChart = echarts.init(barChartRef.value);
  let chartInfo;
  let hasData = false;
  if (
    supplierName &&
    chartData.value?.supplierFaultBelongCount?.[supplierName]
  ) {
    // 显示特定厂商的数据 取supplierFaultBelongCount
    chartInfo = Object.entries(
      chartData.value.supplierFaultBelongCount[supplierName]
    ).map(([label, value]) => ({
      value,
      label,
    }));
    hasData = chartInfo.length > 0;
  } else if (!supplierName && chartData.value?.faultBelongCount) {
    // 显示所有厂商的汇总数据 取faultBelongCount
    chartInfo = Object.entries(chartData.value.faultBelongCount).map(
      ([label, value]) => ({
        value,
        label,
      })
    );
    hasData = chartInfo.length > 0;
  }

  // 如果没有数据，显示无数据提示
  if (!hasData) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    barChart.setOption(option);
    return;
  }

  const option = {
    grid: {
      left: "3%",
      right: "3%",
      bottom: "3%",
      top: "5%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: chartInfo.map((item) => item.label) || [],
      axisLine: {
        lineStyle: {
          color: "#475569",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        margin: 8,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      min: 0,
      splitNumber: 4,
      axisLine: {
        show: true,
        lineStyle: {
          color: "#475569",
        },
      },
      axisLabel: {
        color: "#94a3b8",
        formatter: (value) => Math.round(value),
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: "#334155",
          type: "dotted",
        },
      },
    },
    series: [
      {
        data: chartInfo.map((item) => item.value) || [],
        type: "bar",
        barWidth: "30",
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#5A8DFF" },
            { offset: 1, color: "#2A5FFF" },
          ]),
          borderRadius: [4, 4, 0, 0],
        },
        showBackground: true,
        backgroundStyle: {
          color: "rgba(60, 74, 100, 0.3)",
          borderRadius: [4, 4, 0, 0],
        },
      },
    ],
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
    },
  };

  barChart.setOption(option);
};
const handleResize = () => {
  manufacturerChart && manufacturerChart.resize();
  barChart && barChart.resize();
};
const loading = ref(false);
const outageDashboardData = async () => {
  const params = {
    planShutdown: 0, // 供应链评价这里直接传0
    dashboardStartDate: dateRange.value[0],
    dashboardEndDate: dateRange.value[1],
    dashboardType: "5", // 5: 供应链评价-故障类别设备厂家分析 6:供应链评价-供应商响应分析
    faultType: faultType.value, // 故障类别
  };
  loading.value = true;
  const res = await $api.faultDealDashboard(5, params);
  loading.value = false;
  if (res?.code === 0 && Object.keys(res.data).length > 0) {
    chartData.value = res.data.faultDealBrandAnalyzeDto;
  } else {
    chartData.value = [];
  }
  faultNumTop5.value = res.data.faultDealBrandAnalyzeDto.faultNumTop5;
  initManufacturerBarCharts();
  initBarChart();
};
const handleReset = () => {
  faultType.value = null;
  dateRange.value = getDefaultDateRange();
  outageDashboardData();
};
const faultTypeList = ref([]);
const getFaultTypeList = async () => {
  const res = await $api.faultConfigList({
    configType: 1,
    type: 1, // 1: 非计划 5: 计划
  });
  faultTypeList.value = res.data;
};
onMounted(async () => {
  getFaultTypeList();
  await outageDashboardData();
  initManufacturerBarCharts();
  initBarChart();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  manufacturerChart && manufacturerChart.dispose();
  barChart && barChart.dispose();
});
</script>

<style scoped lang="less">
.stationFailureAnalysis {
  flex: 1;
  min-width: 0;
  height: 480px;
  padding: 0 12px;
  background: #141414;
  border-radius: 4px;
  border: 1px solid #334155;
  color: #e2e8f0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .titleBar {
    flex-shrink: 0;
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    padding: 15px 0;
    border-bottom: 1px solid #334155;
    color: #e2e8f0;
    position: relative;
    flex-shrink: 0;

    .dateRange {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    padding-top: 10px;

    .chartTitle {
      font-size: 14px;
      font-weight: bold;
      color: #e2e8f0;
      margin-bottom: 5px;
      text-align: center;
    }

    .topCharts {
      display: flex;
      height: 200px;
      margin-bottom: 5px;

      .liquidChart {
        flex: 1;
        min-width: 0;

        .chartContainer {
          height: calc(100% - 34px);
          width: 100%;
        }
      }

      .rankList {
        width: 660px;
        flex-shrink: 0;

        .rankItems {
          height: calc(100% - 24px);
          display: flex;
          flex-direction: column;

          .rankItem {
            display: flex;
            align-items: center;
            height: 34px;
            padding: 0 30px;

            .rankNum {
              width: 20px;
              height: 20px;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 12px;
              font-weight: bold;
              margin-right: 10px;

              &.rank1 {
                background-color: #dc2626;
                color: white;
              }

              &.rank2 {
                background-color: #f59e0b;
                color: white;
              }

              &.rank3 {
                background-color: #fbbf24;
                color: white;
              }

              &.rank4 {
                background-color: #3b82f6;
                color: white;
              }

              &.rank5 {
                background-color: #10b981;
                color: white;
              }
            }

            .stationName {
              flex: 1;
              font-size: 14px;
              color: #e2e8f0;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .manufacturer {
              width: 80px;
              font-size: 12px;
              color: #94a3b8;
              text-align: center;
            }

            .faultCount {
              width: 100px;
              font-size: 12px;
              color: #94a3b8;
              text-align: right;
            }
          }
        }
      }
    }

    .bottomChart {
      flex: 1;
      min-height: 0;

      .chartContainer {
        height: calc(100% - 24px);
        width: 100%;
      }
    }
  }

  .noData {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    .noDataText {
      font-size: 14px;
      color: #94a3b8;
    }
  }

  @media (max-width: 1500px) {
    .content {
      .topCharts {
        .rankList {
          width: 550px;
        }
      }
    }
  }
  .faultType {
    display: inline-block;
    font-size: 14px;
    margin-right: 10px;
  }
}
</style>
